<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\PartnerModels\Photo;
use App\Models\PartnerModels\Partner;
use App\Models\PartnerModels\VideoComment;
use Illuminate\Http\Request;
use DB;
use App\Models\PartnerModels\ApiUser;
use App\Components\CodeTools;
use App\Components\Tools;
use App\Models\AdminModels\Message;
use App\Models\AppModels\Api;
use App\Models\AppModels\Auth;
use App\Models\AppModels\CommentUser;
use App\Models\AppModels\Keyword;
use App\Models\AppModels\User;
use App\Models\AppModels\Userinfo;
use App\Models\AppModels\UserLiveVideo;
class YksAppController extends Controller
{
    /**
     *    云快视app控制器
     */

    public function __construct(Request $request)
    {
//        $this->url = Tools::getOneconfig("/config/third.json", array('qiniu', 'qnUrl'));
        $this->params = $request->all();
    }



    //生成token
    public function getToken(){
        $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $count = strlen($base);
        $random = '';
        for ($i=0; $i < 16; $i++) {
         $random.=$base[mt_rand(0,$count-1)];
        }
        return md5($random);
    }

    //云快视移动端登录接口(会员 type2) 合伙人的暂时不弄 要做的时候修改
    public function mobileLogin(Request $request)
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //第一次登录的
        $uip = $request->getClientIp();//获取调用接口的用户的ip
        $soPartner=new Partner();
        $soApiUser = new ApiUser();
        if (isset($data['user'])) {
            //密码加密之后测试
        //    $pwd = \App\Components\Tools::passwordEncryption(trim($data['pwd']));
            $time = date('Y-m-d', time());
            //验证账号
            $re = $soPartner->validAppLogin($data['user'], $data['pwd'],2);
          //  print_r($re);exit();
            //获取对应user_name和type的数据
            $info=$soApiUser->getnameInfo($data['user']);

            if ($re) {//账号密码都对的情况下进行二次判断
                if (!empty($info['equipment_id']) && !empty($info['mac'])) {//设备id存在的话

                    if ($info['equipment_id'] == $data['equipment_id'] && $info['mac'] == $data['mac'] && $data['type']==$info['type'] ) {//设备id相同
                        //设备一致可以登录

                        $tkey = $this->getToken();
                        $soApiUser->saveTaocan(['api_token'=>$tkey], $info['id']);
                        $result = [
                            "code" => 1,
                            "uid" => $re['id'],
                            "token" =>$tkey,
                            "msg" => '登录成功',
                        ];
                        return response()->json($result);
                    } else {
                        //设备不一致
                        $result = [
                            "code" => 0,
                            "msg" => '请使用原设备登录',
                        ];
                        return response()->json($result);
                    }
                } else {//账号密码以及状态时间都符合 没有设备id 新增数据
                    $aipid=$this->firstLogin($data,$re['id'], $uip);
                    $tkey = $this->getToken();
                    $soApiUser->saveTaocan(['api_token'=>$tkey],$aipid);
                    $result = [
                        "code" => 1,
                        "uid" => $re['id'],
                        "token" =>$tkey,
                        "msg" => '登录成功',
                    ];
                    return response()->json($result);
                }
            } else {
                $result = [
                    "code" => 0,
                    "msg" => '账号密码错误',
                ];
                return response()->json($result);
            }
        }
    }
    //第一次登录 在apiuser那里创建
    public function firstLogin($data,$id, $uip)
    {
        $soApiUser = new ApiUser();
        $date = array(
            'pid'=> $id,
            'user_name'=> $data['user'],
            'type' => $data['type'],
            'ip' => $uip,
            'equipment_id' => $data['equipment_id'],
            'mac' => $data['mac'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time()),
        );
     $id=$soApiUser->db_insertGetId($date);
     return isset($id) ? $id: false;
    }

    //查询access_token的方法
    public function getaccesstoken($open_id)
    {
        $sql = " select access_token from pt_dy_access_token where open_id='$open_id' ";
        $token = DB::select($sql);
        return $token;
    }

    //获取移动端首页数据 需要传id  达人/广告/直播 暂无数据
    function  getHomeInfo(){
        //   print_r(1111);
        $code = new CodeTools();
        $soPhoto=new Photo();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //开启判断
        if(!empty($data['id'])){
            $photo=$soPhoto->getAllInfo();//获取首页轮播图数据
            //获取tips
            $tips=$soPhoto->getTips();
            //获取当日获客数量
            $videocount=$soPhoto->getxunpancount($data['id']);
            //获取当日私信的数量（已私信处理数量）
            $videosxcount=$soPhoto->getkeyWordCount($data['id']);
            //获取视频（视频雷达/广告雷达）的获客数量
            $spldcount=$soPhoto->getVideoCount($data['id'],2);
            //获取视频获客的私信处理数量
            $spsxcount=$soPhoto->getVideoSxCount($data['id'],2);
            //获取视频广告雷达的获客数量
            $ggldcount=$soPhoto->getVideoCount($data['id'],3);
            //获取广告雷达的私信处理数量
            $ggsxcount=$soPhoto->getVideoSxCount($data['id'],3);
            //获取达人（账户雷达）获客数量
            $drldcount=$soPhoto->getDrCount($data['id'],1);
            //获取达人（账户雷达）私信数量
            $drsxcount=$soPhoto->getDrSxCount($data['id'],1);
           // print_r($ggsxcount);exit();
            $date=array(
                'photo'=>$photo,
                'tips'=>$tips,
                'videocount'=>$videocount,
                'videosxcount'=>$videosxcount,
                'spldcount'=>$spldcount,
                'spsxcount'=>$spsxcount,
                'ggldcount'=>$ggldcount,
                'ggsxcount'=>$ggsxcount,
                'drldcount'=>$drldcount,
                'drsxcount'=>$drsxcount,
            );
            return $code->apiRturn(1, $date);
        }else{
            return $code->apiRturn(0);
        }

    }
    //接口获取指定时间段的数据
    public function getCommentInfo(){
        $code = new CodeTools();
        $soPhoto=new Photo();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['id'])){
            $keywordcount=$soPhoto->getKeywordCenter($data['id']);
            $videocount=$soPhoto->getVideoCenter($data['id'],2);
            $ggcount=$soPhoto->getVideoCenter($data['id'],3);
            $drcount=$soPhoto->getdrCenter($data['id'],1);
            $date=array(
                'keywordcount'=>$keywordcount,
                'videocount'=>$videocount,
                'ggcount'=>$ggcount,
                'drcount'=>$drcount,
            );
            return $code->apiRturn(1, $date);
            //获取关键词雷达客户（当日/7日/30日/总数据）、

            //获取关键词雷达私信数据（当日/7日/30日/总数据）、
        }else{
            return $code->apiRturn(0);
        }

    }
    // 接口 获取我的页面的相关
    public function getSelfInfo(){
        $code = new CodeTools();
        $soPartner=new Partner();
        $soVideoComment=new VideoComment();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if (!empty($data['id'])){ //目前判断id,type(会员还是合伙人) 所有数据更加id查询
            $info=$soPartner->getSelfInfo($data['id']);
            //获取总获客条数
            $allXunpanCount=$soVideoComment->getXunPan($data['id']);
            $data=array(
                'userinfo'=>$info,
                'allXunpanCount'=>$allXunpanCount,
            );
            return $code->apiRturn(1, $data);
        }else{
            return $code->apiRturn(0);
        }
    }
//接口 修改密码
public function editPassWord(){
    $code = new CodeTools();
    $soPartner=new Partner();
    $soVideoComment=new VideoComment();
    $body = file_get_contents("php://input");//获取提交过来的数据
    $data = json_decode($body, true); //对获取的数据进行解析
   // print_r($data);exit();
    if(!empty($data['id']) && !empty($data['newpwd']) && !empty($data['oldpwd'])){//判断存在id new pwd  旧密码oldpwd
        //检查是否存在对应的id账号
        $checkpwd=$soPartner->validAdminLogin($data['id'],$data['oldpwd'],$data['type']);
        if(!empty($checkpwd)){//验证通过
            //设置新密码
           if($soPartner->db_update('', $data['id'], ['pwd' => \App\Components\Tools::passwordEncryption($data['newpwd'])])){
               return $code->apiRturn(1);//成功回调
           } else{
               return $code->apiRturn(0); //失败回调
           }
        }else{
            return $code->apiRturn(0);//验证失败回调
        }
    }else{
        return $code->apiRturn(0);//传递参数错误回调
    }
}
    //我的页面 高级功能
    public function editGjRoul(){
        $code = new CodeTools();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['id']) ){//如果id为空 返回错误
            if(!empty($data['roul'])){//如果手机权限修改存在
                //修改对应表
                return $code->apiRturn(1);
            } elseif(!empty($data['zhibo'])){
                //修改对应表字段
                return $code->apiRturn(1);
            }elseif(!empty($data['auto'])){
                //修改对应表字段
                return $code->apiRturn(1);
            }else{
                //传了id但是没存字段 返回数据错误
                return $code->apiRturn(0);
            }
        }else{//不存在id
            return $code->apiRturn(0);//传递参数错误回调
        }
    }
    //重置密码的接口
    public function resetPwd(){
        $code = new CodeTools();
        $soPartner=new Partner();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        if(!empty($data['id']) && !empty($data['newpwd'])){
            if($soPartner->db_update('', $data['id'], ['pwd' => \App\Components\Tools::passwordEncryption($data['newpwd'])])){
                return $code->apiRturn(1);
            }
        }else{
            return $code->apiRturn(0);
        }
    }

    function getMessage(){
        $code = new CodeTools();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $soMessage=new Message();
        if(!empty($data['type'])){//存在消息类型
            $date=$soMessage->getAppMseeage($data);
            return $code->apiRturn(1, $date);
        }else{
            return $code->apiRturn(0);
        }
    }
    //给用户添加内容关键词
    function addKeyword()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $re = $code->apiRturn(0);

        if (empty($data['pid']) && empty($data['type']) && empty($data['content'])) {
            return $code->apiRturn(0);
        }
        $Keyword = new Keyword();
        $Auth = new Auth();
        $userList = $Auth->checkUserinfo($data['pid']);
        if (empty($userList)) {//如果不存在用户
            return $code->apiRturn(0);
        }
        //查询是否存在数据 存入方法一件写了
        $re = $Keyword->findKeyword($data['pid'], $data['content']);
        if ($re) {//如果不存在用户
            return $code->apiRturn(0);
        }
        $date = array(
            'name' => $data['content'],
            'user_id' => $data['pid'],
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s', time()),
            'update_time' => date('Y-m-d H:i:s', time()),
        );
        $cd = $Keyword->saveApiKey($date, $data['type']);
        if ($cd) {
            return $code->apiRturn(1);
        }
    }

    //获取关键词页面数据 (没有分页直接传的)
    public function getKeywordInfo()
    {
        $code = new CodeTools();
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //  print_r(111);exit();
        //判断数据是否正常
        $soApi = new Api();
        if (empty($data['pag']) && empty($data['uid']) && empty($data['limit'])) {
            return $code->apiRturn(0);
        } else {
            $date = $soApi->getKeyData($data);
            return $code->apiRturn(1, $date);
        }
    }

    //获取询盘数据接口
    public function getXunPaninfo()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //  print_r($data);exit();
        $soApi = new Api();
        $code = new CodeTools();
        if (empty($data['id'])) {//数据不正确有空值
            return $code->apiRturn(0);
        } else {
            $date = $soApi->getPageData($data);
            return $code->apiRturn(1, $date);
            //把传过来的值做筛选组合
        }
    }


    //监控雷达界面 主页监控 类型1 主页雷达 2账号雷达
    public function getleidaInfo()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        //  print_r($data);exit();
        $soApi = new Api();
        if (empty($data['id'])) {

            return $code->apiRturn(0);
        } else {
            $date = $soApi->selectData($data);
            return $code->apiRturn(1, $date);
        }
    }
    //直播雷达界面数据获取
    public function getLiveInfo(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $soApi = new Api();
        if(empty($data['id'])){//判断是否存在 id id为空直接返回错误
            return $code->apiRturn(0);
        }else{
            $date = $soApi->getLiveData($data);
            return $code->apiRturn(1, $date);
        }
    }
    //直播评论拉取
    function addLived(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        if(empty($data['video_id'])){
            return $code->apiRturn(0);
        }else{
            $liveComment=new UserLiveVideo();
            $video_id = isset($data['video_id']) ? $data['video_id'] : 0;
            $page = isset($data['page']) && intval($data) ? intval($data) : 1;
            $filter=isset($data['filter']) ? intval($data['filter']) : 99;
            $weekTime=isset($data['weekTime']) ? intval($data['weekTime']) : 99;
            $gende=isset($data['gende']) ? intval($data['gende']) : 99;
            // echo "<pre/>";print_r($this->params);exit;
            $re=$liveComment->liveinfoComment($video_id,$page,$filter,$weekTime,$gende);
            if($re){
                return $code->apiRturn(1,$re);
            }
            return $code->apiRturn(0);
        }
        //echo json_encode(["code" => 0, "html" => $re['html'], "nextPage" => $re['nextPage']]);exit;
    }
    //直播评论状态修改
    function liveCommentStatus(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $liveComment=new UserLiveVideo();
        if(!empty($data['kid']) && !empty($data['status'])){//数据不为空
            $returnUp = $liveComment->saveStatus($data['kid'], ['status' => $data['status']]);
            return $code->apiRturn(1);
        }else{
            return $code->apiRturn(0);
        }
    }
    //修改雷达状态（账号视频广告雷达 ）
    public function editLeiDa(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        //  print_r($data);exit();
        $code = new CodeTools();
        $user = new User();
        //判断是否存在 用户id以及雷达id 和状态
        if(!empty($data['uid']) && !empty($data['ldid'])) {
            $re=$user->editLeiDa($data);
          //  print_r($re);exit();
            if ($re){//如果修改失败
                return $code->apiRturn(1);
            }else{
                return $code->apiRturn(0,444);
            }
        }else{
            return $code->apiRturn(0,555);
        }
    }
    //修改关键词状态
    public function editKeyword(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $user = new User();
        //判断是否存在 用户id以及雷达id 和状态
        if(!empty($data['uid']) && !empty($data['keyid']) && !empty($data['type'])) {
            $re=$user->editKeyword($data);
            //   print_r($re);exit();
            if ($re){//如果修改失败
                return $code->apiRturn(1);
            }else{
                return $code->apiRturn(0);
            }
        }else{
            return $code->apiRturn(0);
        }
    }

    //修改询盘状态
    function editXunpanStatus(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $oKeyword = new Keyword();
        if(!empty($data['kid']) ){
            $result = $oKeyword->editStatus($data['kid'],$data['status']);
            if ($result){
                return $code->apiRturn(1);
            }
            return $code->apiRturn(0);
        }else{
            return $code->apiRturn(0);
        }
    }
    //修改直播数据状态
    function editLiveStatus(){
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $oUserLiveVideo = new UserLiveVideo();
        if(!empty($data['kid']) ){
            $result = $oUserLiveVideo->editStatus($data['kid'],$data['status']);
            if ($result){
                return $code->apiRturn(1);
            }
            return $code->apiRturn(0);
        }else{
            return $code->apiRturn(0);
        }
    }
    //修改账号/主页/广告 雷达数据状态
    //主页、视频	评论处理状态操作
    function ldcommentStatus()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $CommentUser = new CommentUser();
        if(!empty($data['kid']) ){
            $returnUp = $CommentUser->saveStatus($data['kid'], ['status' => $data['status']]);
            if ($returnUp){
                return $code->apiRturn(1);
            }
            return $code->apiRturn(0);
        }else{
            return $code->apiRturn(0);
        }
    }

    //获取页面的获客数据
    public function getVideoComment()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $data = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $soApi = new Api();
        if (empty($data['type']) && empty($data['id']) && empty($data['video_id'])) {
            return $code->apiRturn(0);
        } else {
            $date = $soApi->getVideoViewComment($data);
            return $code->apiRturn(1, $date);
        }
    }
    //----------------------------------------添加广告雷达的接口
    //添加广告雷达数据
    function addadvert()
    {       //role_id info登录后的类型：会员、合伙人 为0，否则为 后台的权限id'
        $body = file_get_contents("php://input");//获取提交过来的数据
        $date = json_decode($body, true); //对获取的数据进行解析
        $user = new User();
        $code = new CodeTools();
        if (empty($date['pid']) && empty($date['url'])) {//数据有空值
            return $code->apiRturn(0);
        }
        $system_type = isset($date['role_id']) ? intval($date['role_id']) : 0;
        $partner_id = $date['pid'];
        $url = $date['url'];
        //查询是否存在这个用户
        $checkuser = $user->checkUser($partner_id);
        if (empty($checkuser)) {
            return $code->apiRturn(0);
        }
        //    $url = isset($this->params['info_url']) && $this->params['info_url'] ? $this->params['info_url'] : $this->returnJson(1, '请输入广告分享的链接地址');

        //取出地址
        $pgma = "/http(s):\/\/v.douyin.com\/[a-zA-z0-9]{3,}\//";

        preg_match($pgma, $url, $urlArr);
        //  $info_vurl = isset($urlArr[0]) && $urlArr[0] ? $urlArr[0] : $this->returnJson(1, '网址错误');//短链接
        $info_vurl = isset($urlArr[0]) && $urlArr[0] ? $urlArr[0] : $code->apiRturn(0);//短链接

        $real_url = $this->getContents($info_vurl);//实际网页链接

        // !$real_url ? $this->returnJson(1, '网络繁忙，请稍后重试') : '';
        !$real_url ? $code->apiRturn(0) : '';

        $item_ids = $this->cut_str($real_url, '/video/', '?', 7);//取出 /video/  下的数字 ID

        $getUrl = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" . $item_ids;//接口地址
        $userInfoData = $this->douyinContents($getUrl);
        // print_r($userInfoData);exit();
        $data = array(
            'info_id' => isset($userInfoData['item_list'][0]['author']['unique_id']) && !empty($userInfoData['item_list'][0]['author']['unique_id']) ? $userInfoData['item_list'][0]['author']['unique_id'] : $userInfoData['item_list'][0]['author']['short_id'],
            'info_name' => isset($userInfoData['item_list'][0]['author']['nickname']) ? htmlspecialchars($userInfoData['item_list'][0]['author']['nickname'], ENT_QUOTES) : '',
            'info_img' => isset($userInfoData['item_list'][0]['video']['cover']['url_list'][0]) ? $userInfoData['item_list'][0]['video']['cover']['url_list'][0] : '',
            'info_support' => isset($userInfoData['item_list'][0]['statistics']['digg_count']) ? htmlspecialchars($userInfoData['item_list'][0]['statistics']['digg_count'], ENT_QUOTES) : '',
            'info_opus' => isset($userInfoData['item_list'][0]['statistics']['comment_count']) ? $userInfoData['item_list'][0]['statistics']['comment_count'] : '',
            'info_signature' => isset($userInfoData['item_list'][0]['desc']) ? $userInfoData['item_list'][0]['desc'] : '',
            'info_fans' => isset($userInfoData['item_list'][0]['statistics']['share_count']) ? $userInfoData['item_list'][0]['statistics']['share_count'] : '',
            'info_url' => $getUrl,
            'info_vurl' => $info_vurl,
            'info_date' => date('Y-m-d H:i:s', time())
        );
        // echo "<pre/>";print_r($data);exit();

        //查询询盘数量、今天是否重新加入过	必须在更新、添加之前查询
        $Auth = new Auth();
        $CommentUser = new CommentUser();
        $num = $Auth->checkInq($partner_id);
        $info_date = $CommentUser->selectInfodata($partner_id, $item_ids, 3);
        $dateTime = date('Y-m-d', strtotime($info_date)) == date('Y-m-d') ? false : true;

        //更新、添加数据
        $userInfo = new Userinfo();
        $values = array(3, $item_ids, $system_type, $partner_id);
        $returnId = $userInfo->insertUser($data, $values);

        if ($returnId) {
            if ($num && $dateTime) {
                $url = $_SERVER['HTTP_HOST'] . "/hand/index";
                $arr = [
                    'partner_id' => $partner_id,
                    'video_id' => $item_ids,
                    'title' => isset($userInfoData['item_list'][0]['desc']) ? $userInfoData['item_list'][0]['desc'] : '',
                    'advert' => true,
                ];
                $this->postUrl($url, $arr);
            }
//            $data=JSON.stringify(obj);
            return $code->apiRturn(1);
        }
        return $code->apiRturn(0);
    }

    //-------------------------添加视频监控链接
    function addVideoList()
    {
        //添加视频分享数据
        $body = file_get_contents("php://input");//获取提交过来的数据
        $date = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        if (empty($date['pid']) && empty($date['url'])) {//数据有空值
            return $code->apiRturn(0);
        }
        $system_type = isset($date['role_id']) ? intval($date['role_id']) : 0;
        $partner_id = $date['pid'];

        //判断用户有没有添加内容关键词e
        $sql = "select * from pt_keyword_conent where user_id = ? and status=1 order by status desc,update_time desc";
        $re = DB::select($sql, [$partner_id]);
        if (!$re) {
            return $code->apiRturn(0);
            // $this->returnJson(1, '请先添加内容关键词');
        }

        //判断视频雷达剩余数是否足够
        $user = new User();
        $num = $user->monitorVideo();
        !$num ? $code->apiRturn(0) : '';
        //检查用户id是否存在
        $checkuser = $user->checkUser($partner_id);
        if (empty($checkuser)) {
            return $code->apiRturn(0);
        }
        $url = $date['url'];
        //取出地址
        $pgma = "/http(s):\/\/v.douyin.com\/[a-zA-z0-9]{3,}\//";

        preg_match($pgma, $url, $urlArr);
        $info_vurl = isset($urlArr[0]) && $urlArr[0] ? $urlArr[0] : $code->apiRturn(0);//短链接

        $real_url = $this->getContents($info_vurl);//实际网页链接
        // print_r($real_url);exit();
        !$real_url ? $code->apiRturn(0) : '';

        $item_ids = $this->cut_str($real_url, '/video/', '?', 7);//取出 /video/  下的数字 ID

        $getUrl = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" . $item_ids;//接口地址
        $userInfoData = $this->douyinContents($getUrl);
        // print_r($userInfoData);exit();
        $data = array(
            'info_id' => isset($userInfoData['item_list'][0]['author']['unique_id']) && !empty($userInfoData['item_list'][0]['author']['unique_id']) ? $userInfoData['item_list'][0]['author']['unique_id'] : $userInfoData['item_list'][0]['author']['short_id'],
            'info_name' => isset($userInfoData['item_list'][0]['author']['nickname']) ? htmlspecialchars($userInfoData['item_list'][0]['author']['nickname'], ENT_QUOTES) : '',
            'info_img' => isset($userInfoData['item_list'][0]['video']['cover']['url_list'][0]) ? $userInfoData['item_list'][0]['video']['cover']['url_list'][0] : '',
            'info_support' => isset($userInfoData['item_list'][0]['statistics']['digg_count']) ? htmlspecialchars($userInfoData['item_list'][0]['statistics']['digg_count'], ENT_QUOTES) : '',
            'info_opus' => isset($userInfoData['item_list'][0]['statistics']['comment_count']) ? $userInfoData['item_list'][0]['statistics']['comment_count'] : '',
            'info_signature' => isset($userInfoData['item_list'][0]['desc']) ? $userInfoData['item_list'][0]['desc'] : '',
            'info_fans' => isset($userInfoData['item_list'][0]['statistics']['share_count']) ? $userInfoData['item_list'][0]['statistics']['share_count'] : '',
            'info_url' => $getUrl,
            'info_vurl' => $info_vurl,
            'info_date' => date('Y-m-d H:i:s', time())
        );
        // echo "<pre/>";print_r($data);exit();

        //查询询盘数量、今天是否重新加入过	必须在更新、添加之前查询
        $Auth = new Auth();
        $CommentUser = new CommentUser();
        $num = $Auth->checkInq($partner_id);
        $info_date = $CommentUser->selectInfodata($partner_id, $item_ids, 2);
        $dateTime = date('Y-m-d', strtotime($info_date)) == date('Y-m-d') ? false : true;

        //更新、添加数据
        $userInfo = new Userinfo();
        $values = array(2, $item_ids, $system_type, $partner_id);
        $returnId = $userInfo->insertUser($data, $values);

        if ($returnId) {
            if ($num && $dateTime) {
                $url = $_SERVER['HTTP_HOST'] . "/hand/index";
                $arr = [
                    'partner_id' => $partner_id,
                    'video_id' => $item_ids,
                    'title' => isset($userInfoData['item_list'][0]['desc']) ? $userInfoData['item_list'][0]['desc'] : '',
                ];
                $this->postUrl($url, $arr);
            }

            return $code->apiRturn(1);
        }
        return $code->apiRturn(0);
    }
    //添加主页分享数据
    function addinfo()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $date = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        if (empty($date['pid']) && empty($date['url'])) {//数据有空值
            return $code->apiRturn(0);
        }
        $system_type = isset($date['role_id']) ? intval($date['role_id']) : 0;
        $partner_id = $date['pid'];
        //判断主页雷达剩余数是否足够
        $user = new User();
        $numInfo = $user->monitorInfo();
        $numInfo ? '' : $code->apiRturn(0);
        //检查用户id是否存在
        $checkuser = $user->checkUser($partner_id);
        if (empty($checkuser)) {
            return $code->apiRturn(0);
        }
        $url = $date['url'];
        !$url ? $code->apiRturn(0) : '';
        //取出地址
        $pgma = "/http(s):\/\/v.douyin.com\/[a-zA-z0-9]{3,}\//";
        preg_match($pgma, $url, $urlArr);
        $info_vurl = isset($urlArr[0]) && $urlArr[0] ? $urlArr[0] : $code->apiRturn(0);//短链接

        $real_url = $this->getContents($info_vurl);//实际网页链接
        !$real_url ? $code->apiRturn(0) : '';


        $sec_uid = "sec_uid=" . $this->cut_str($real_url, '/user/', '?', 6);//取出主页sec_uid

        $getUrl = "https://www.iesdouyin.com/web/api/v2/user/info/?" . $sec_uid;//接口地址
        $userInfoData = $this->douyinContents($getUrl);

        $data = array(
            'info_id' => isset($userInfoData['user_info']['unique_id']) && !empty($userInfoData['user_info']['unique_id']) ? $userInfoData['user_info']['unique_id'] : $userInfoData['user_info']['short_id'],
            'info_name' => isset($userInfoData['user_info']['nickname']) ? htmlspecialchars($userInfoData['user_info']['nickname'], ENT_QUOTES) : '',
            'info_img' => isset($userInfoData['user_info']['avatar_thumb']['url_list'][0]) ? $userInfoData['user_info']['avatar_thumb']['url_list'][0] : '',
            'info_signature' => isset($userInfoData['user_info']['signature']) ? htmlspecialchars($userInfoData['user_info']['signature'], ENT_QUOTES) : '',
            'info_follow' => isset($userInfoData['user_info']['following_count']) ? $userInfoData['user_info']['following_count'] : '',
            'info_fans' => isset($userInfoData['user_info']['follower_count']) ? $userInfoData['user_info']['follower_count'] : '',
            'info_support' => isset($userInfoData['user_info']['total_favorited']) ? $userInfoData['user_info']['total_favorited'] : '',
            'info_opus' => isset($userInfoData['user_info']['aweme_count']) ? $userInfoData['user_info']['aweme_count'] : '',
            'info_url' => $getUrl,
            'info_vurl' => $info_vurl,
            'info_date' => date('Y-m-d H:i:s', time())
        );
        // echo "<pre/>";print_r($userInfoData);exit();

        //查询询盘数量、今天是否重新加入过	必须在更新、添加之前查询
        $Auth = new Auth();
        $CommentUser = new CommentUser();
        $num = $Auth->checkInq($partner_id);    //询盘剩余数
        $info_date = $CommentUser->selectInfodata($partner_id, $sec_uid, 1);
        $dateTime = date('Y-m-d', strtotime($info_date)) == date('Y-m-d') ? false : true;    //更新时间是否是今天 如果是今天  为 false  不是  为 true

        //更新、添加数据
        $userInfo = new Userinfo();
        $values = array(1, $sec_uid, $system_type, $partner_id);
        $returnId = $userInfo->insertUser($data, $values);

        if ($returnId) {
            if ($num && $dateTime) {
                $mealName = $userInfo->selectMeal($partner_id);
                $info_number = Tools::getOneconfig('/config/inquiry.json', [$mealName, 'info_number']) ? Tools::getOneconfig('/config/inquiry.json', [$mealName, 'info_number']) : 1;

                $getVidoe = "https://www.iesdouyin.com/web/api/v2/aweme/post/?{$sec_uid}&count=100";
                $videoList = $this->douyinContents($getVidoe);
                $arr = [
                    'partner_id' => $partner_id,
                    'type' => $returnId,
                ];

                if (!empty($videoList['aweme_list'])) {
                    foreach ($videoList['aweme_list'] as $k => $v) {
                        $tDaytime = false;
                        if (!empty($v['statistics']['comment_count']) && $v['statistics']['comment_count'] >= 1) {
                            $tDaytime = true;
                        }

                        if ($tDaytime && --$info_number >= 0) {
                            $arr['video_arr'][] = $v['aweme_id'];
                            $arr['title_arr'][] = $v['desc'];
                        }
                    }
                }
                // echo '<pre/>';print_r($arr);exit;
                $url = $_SERVER['HTTP_HOST'] . "/hand/info";
                $this->postUrl($url, $arr);
            }

            return $code->apiRturn(1);
        }
        return $code->apiRturn(0);
    }
    //----------------------------添加直播间雷达
    /*
  * 调用获取直播数据的接口，同步数据的方式另选
  *$count 直播监控数量上限（目前写死）然后再确定是套餐设置还是什么
  *  */
    function addlive()
    {
        $body = file_get_contents("php://input");//获取提交过来的数据
        $date = json_decode($body, true); //对获取的数据进行解析
        $code = new CodeTools();
        $system_type = isset($date['role_id']) ? intval($date['role_id']) : 0;
        if(empty($date['pid']) && empty($date['url'])){//不存在用户id或者url链接
            return $code->apiRturn(0);
        }else{
            //判断视频雷达剩余数是否足够
            $count=5;
            $user = new User();
            $solive=new UserLiveVideo();
            $num = $user->liveUseInfo($count);
            if(!$num){
                return $code->apiRturn(0);
            }
            //获取直播的roomid
            $url = $date['url'];
            //取出地址
            $pgma = "/http(s):\/\/v.douyin.com\/[a-zA-z0-9]{3,}\//";

            preg_match($pgma, $url, $urlArr);
            $info_vurl = $urlArr[0];
            if(!$info_vurl){
                return $code->apiRturn(0);
            }
            $real_url = $this->getContents($info_vurl);//实际网页链接
            if(!$real_url){
                return $code->apiRturn(0);
            }
            //获取的具体直播房间号
            $room_id = $this->cut_str($real_url, 'room_id=', '&', 8);//取出 /video/  下的数字 ID
            //请求接口获取回调的一个参数 存库 然后之后根据那个参数来获取用户的直播数据并存库

            $sta = mb_strpos($url,'【');
            $end = mb_strpos($url,'】正在直播');
            $title = $sta && $end ? mb_substr($url,$sta+1,$end-$sta-1) : '';
            // echo "<pre/>";print_r($title);exit();

            $values=[$room_id,$system_type,$date['pid']];
            $data=[
                'info_name'=>htmlspecialchars($title,ENT_QUOTES),
                'update_time'=>date('Y-m-d H:i:s') ,
                'room_url'=>$real_url,
            ];
            $returnId=$solive->saveLive($data,$values);
            if ($returnId){
                return $code->apiRturn(1);
            }else{
                return $code->apiRturn(0);
            }
        }
    }






    /**
     *    获取评论 get 请求 重试机制
     *    checkTest    需要正确匹配存在的字符串 否则 开启重试
     *    $retry        重试retry-1次    默认3次
     *    sleep        休眠时间 秒
     */
    function getWhileJson($url, $checkTest = '"status": "success", "code": 200,', $retry = 4, $sleep = 20)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);//连接后等待时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);//连接前等待时间
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
        curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $output = curl_exec($ch);

        if ($checkTest) {
            while (!strpos($output, $checkTest) && --$retry > 0) {
                sleep($sleep);
                $output = curl_exec($ch);
            }
        }

        curl_close($ch);
        return json_decode($output, true);
    }

    //获取真实地址
    function getContents($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  //是否抓取跳转后的页面
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        $res = curl_exec($ch);
        $info = curl_getinfo($ch);
        $retURL = $info['url'];   // 跳转后的 URL 信息
        curl_close($ch);
        return $retURL;
    }

    /*截取指定位置字符串
    *	$str 要截取的字符串   $start 截取开始位置    $end 截取结束位置   $number 从第几个取   $fristStr 匹配字符串的位置
    */
    function cut_str($str, $start, $end, $number)
    {
        $code = new CodeTools();
        $fristStr = strpos($str, $start);
        if ($fristStr === false) {
            $code->apiRturn(0);
            //  $this->returnJson(1, '请检查地址是否正确：主页链接 or 视频链接');
        }
        $sta = mb_substr($str, $fristStr + $number);
        return mb_substr($sta, 0, strpos($sta, $end));
    }

    //获取数据
    function douyinContents($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        $res = curl_exec($ch);
        curl_close($ch);
        return json_decode($res, true);
    }

    //异步操作 抓取视频评论
    function postUrl($url, $data)
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($data)))
        );

        //执行命令
        $json = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return json_decode($json, true);
    }
}